package netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;


/**
 * 本质仍旧是nio，但不同是使用了多线程的处理方式
 */
public class NettyServer {
    private final int port;

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        // 创建主从EventLoopGroup
        // 多个接待员，本质就是多线程
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 多个业务员
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建ServerBootstrap
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new StringDecoder(),  // 解码ByteBuf到String
                                    new StringEncoder(),  // 编码String到ByteBuf
                                    new NettyServerHandler());  // 自定义处理器
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)          // 连接队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // 保持长连接

            // 绑定端口并启动
            ChannelFuture f = b.bind(port).sync();

            System.out.println("Netty服务器启动，监听端口: " + port);

            // 等待服务器关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅关闭EventLoopGroup
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyServer(8080).run();
    }
}
